package mashuaiproject.mashuaiproject.controller;

import mashuaiproject.mashuaiproject.mapper.QuesionMapper;
import mashuaiproject.mashuaiproject.mapper.SaveQuesionMapper;
import mashuaiproject.mashuaiproject.model.Save;
import mashuaiproject.mashuaiproject.model.Users;
import mashuaiproject.mashuaiproject.serivce.JMontiorSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.SavepointManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class SaveQuesionController {
    @Autowired
    private SaveQuesionMapper saveQuesionMapper;
    @Autowired
    private JMontiorSerivce jMontiorSerivce;
    @GetMapping("/savequesion")
    @ResponseBody
    public Map<String,Object> SaveQuesions(@RequestParam("quesionId")Integer quesionId, HttpServletRequest request){

        Map<String,Object> map=new HashMap<>();
        //判断用户是否为空
        Users user = (Users) request.getSession().getAttribute("user");
        if(user==null){
            map.put("codes","noLogin");
            return map;//未登录
        }
        //首先要判断下是否已经点赞过。(如果save表中当前的id有这个用户，说明已经点赞)
        Save save2=saveQuesionMapper.selectUserId(quesionId,user.getId());
        if(save2!=null){
            //说明用户已经过
            map.put("codes","isSave");
            return map;
        }
        //插入数据库
        //获取当的用户
        Save save=new Save();
        save.setUser_id(user.getId());
        save.setQuesion_id(quesionId);
        //获取文章对应主人的id
        Integer father_id=saveQuesionMapper.selectById(quesionId);
        save.setFather_id(father_id);
        save.setGmt_create(System.currentTimeMillis());
        //将数据插入
        Integer insertSave=saveQuesionMapper.insertSave(save);

        if(insertSave!=0){
            //添加收藏
            jMontiorSerivce.checkHasGuaZhu(user.getId(),father_id,"saveAdd");
            jMontiorSerivce.Upleave(user.getId());
            Integer insert =jMontiorSerivce.insertDongtai(user.getId(),5,quesionId);//用户id，动态类型，不集体类型

            //然后在更新来当前的博主的收藏数（like_count数量）
            Integer updateLike_count=saveQuesionMapper.upateLikeCOunt(quesionId);
            Integer likeCount=saveQuesionMapper.selectLike(quesionId);
            map.put("likeCount",likeCount);
            //在查找出当前博客的粉丝量
            map.put("codes","succes");

            return map;
        }
        return map;
    }
}
